終於到了這一天!!
昨天已經建立了 Input Devices ,今天就要把 scan Barcode 的功能加上
var forPreview : UIView! = UIView()
var codeLabel : UILabel! = UILabel()
var typeLabel : UILabel! = UILabel()
let fullSize = UIScreen.main.bounds.size
forPreview.frame = CGRect(x: ((fullSize.width-300)/2), y: 200, width: 300 , height: 200)
forPreview.backgroundColor = UIColor.gray
codeLabel.frame = CGRect(x: ((fullSize.width-200)/2), y: 450, width: 200, height: 50)
typeLabel.frame = CGRect(x: ((fullSize.width-200)/2), y: 550, width: 200, height: 50)
codeLabel.backgroundColor = UIColor.darkGray
typeLabel.backgroundColor = UIColor.gray
...
self.view.addSubview(forPreview)
self.view.addSubview(codeLabel)
self.view.addSubview(typeLabel)
let session :AVCaptureSession! = AVCaptureSession()
let deviceInput = DeviceInput()
let previewLayer = AVCaptureVideoPreviewLayer()
let output = AVCaptureMetadataOutput()
func settingPreviewLayer() {
previewLayer.frame = forPreview.bounds
previewLayer.session = session
previewLayer.videoGravity = .resizeAspectFill
forPreview.layer.addSublayer(previewLayer)
}
settingPreviewLayer()
將 “.backWildAngleCamera” 連結到 input
session.addInput(deviceInput.backWildAngleCamera!)
開啟 “output” ,並且設定”接受所有可辨識的meta資料”
session.addOutput(output)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.global())
開始串流
session.startRunning()
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
for metaData in metadataObjects {
if let data = metaData as? AVMetadataMachineReadableCodeObject {
DispatchQueue.main.async {
self.codeLabel.text = data.stringValue
self.typeLabel.text = data.type.rawValue
}
}
}
}
class ViewController: UIViewController , AVCaptureMetadataOutputObjectsDelegate{
session.addOutput(output) 必須要寫在 “output.meatadataObjectTypes” 和 “output.setMetadataObjectDelegate”前面
,因為要將Input與 output開啟,這樣後續才知道 input資料是哪一種類型,